﻿#region Using namespaces

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;

using QuickGraph;
using QuickGraph.Serialization;

using BOL.IO;

#endregion

namespace BOL.Apps.GeneNetworkBrowser.IO
{
    public class NetworkXMLReader : IReader<Network>
    {
        #region Private variables

        private FileStream _fs;

        #endregion

        #region Constructors

        public NetworkXMLReader(FileStream fs)
        {
            this._fs = fs;
        }

        public NetworkXMLReader(string path) : this(new FileStream(path, FileMode.Open)) { }

        #endregion

        #region Public methods

        public Network Read()
        {
            using(var xr = XmlReader.Create(_fs))
            {
                return SerializationExtensions.DeserializeFromXml<Gene, Relation, Network>(
                    xr,
                    "Network",
                    "Gene",
                    "Relation",
                    "http://cbmi.wustl.edu/GeneNetworkBrowser",
                    network => new Network(),
                    gene => new Gene(Int32.Parse(xr.GetAttribute("Id"))),
                    x => new Relation(
                        new Gene(Int32.Parse(x.GetAttribute("Source"))),
                        new Gene(Int32.Parse(x.GetAttribute("Target"))),
                        UInt32.Parse(x.GetAttribute("RelationType")))
                );
            }
        }

        public void Close()
        {
            _fs.Close();
        }

        #endregion
    }
}
